'''
BM11 链表相加(二)
'''



class ListNode:
    def __init__(self,val,next = None):
        self.val = val
        self.next = next




class Soiution:
    def reverse(self,head):
        if head == None:
            return head
        pre = None
        cur = head

        while cur:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next
        return pre
    def addInList(self, head1: ListNode, head2: ListNode) -> ListNode:
        if head1 == None:
            return head2
        if head2 == None:
            return head1

        head1 = self.reverse(head1)
        head2 = self.reverse(head2)

        #添加一个表头
        res = ListNode(-1)
        head = res
        #进位符号
        carry = 0
        while head1 != None or head2 != None or carry != 0:
            val1 = 0 if head1 == None else head1.val
            val2 = 0 if head2 == None else head2.val
            temp = val1+val2+carry
            carry = int(temp/10)
            temp = temp%10

            head.next = ListNode(temp)
            head = head.next

            if head1:
                head1 = head1.next
            if head2:
                head2 = head2.next
        head = self.reverse(res.next)
        return head



def printList(node: ListNode):
    while node:
        print(node.val, end="->" if node.next else "\n")
        node = node.next

if __name__ == "__main__":
    phead1 = ListNode(1,ListNode(3,ListNode(5,ListNode(10,ListNode(18)))))
    phead2 = ListNode(2,ListNode(3,ListNode(7,ListNode(8,ListNode(9)))))


    solution = Soiution()
    printList(solution.addInList(phead1,phead2))